package com.example.hrm.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.hrm.service.UserAuthenticationService;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    private UserAuthenticationService userAuthenticationService;

    @PostMapping("/login")
    public Map<String, String> login(@RequestBody Map<String, String> credentials){
        String username = credentials.get("username");
        String password = credentials.get("password");
        return userAuthenticationService.login(username, password);
    }
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody Map<String, String> userData){
        String username = userData.get("username");
        String password = userData.get("password");
        String email = userData.get("email");
        String phone = userData.get("phone");
        Map<String, Object> response = new HashMap<>();
        try {
            userAuthenticationService.register(username, password, email, phone);
            response.put("success", true);
            response.put("message", "注册成功");
        } catch (RuntimeException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }
    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpServletRequest request){
        try{
            //获取请求头的token
            String token = request.getHeader("Authorization");
            if (token!=null&&token.startsWith("Bearer ")){
                token = token.substring(7);
                userAuthenticationService.logout(token);
            }
            return ResponseEntity.ok("登出成功");
        }catch (Exception e){
            return ResponseEntity.status(500).body("登出失败"+ e.getMessage());
        }
    }

    @PostMapping("/reset-password")
    public Map<String, Object> resetPassword(@RequestBody Map<String, String> data) {
        String username = data.get("username");
        String newPassword = data.get("newPassword");
        Map<String, Object> response = new HashMap<>();
        try {
            userAuthenticationService.resetPassword(username, newPassword);
            response.put("success", true);
            response.put("message", "密码已成功重置为BCrypt格式");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }
}
